package cn.kgc.controllers;

import cn.kgc.pojo.House;
import cn.kgc.pojo.HouseType;
import cn.kgc.service.HouseService;
import cn.kgc.service.HouseTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/main2")
public class Exam {
    @Autowired
    private HouseService houseService;
    @Autowired
    private HouseTypeService houseTypeService;

    @RequestMapping("/findAll")
    public String findAll(@RequestParam(value="type", required = false, defaultValue="0")String type, Model model, @RequestParam(value="pageIndex",required = false, defaultValue="1")Integer pageIndex){
        List<HouseType> houseTypeList = houseTypeService.HOUSE_TYPE_LIST();
        PageHelper.startPage(pageIndex, 3);
        List<House> houseList = houseService.houseList(type);
        PageInfo<House> houses = new PageInfo<>(houseList);
        System.out.println("数据列表如下:");
        for (House house : houseList) {
            System.out.println(house.toString());
        }
        model.addAttribute("typeList", houseTypeList);
        model.addAttribute("pageInfo", houses);

        return "index2";
    }

    @RequestMapping("findType")
    public String findType(House house, Model model){
        List<HouseType> houseTypeList = houseTypeService.HOUSE_TYPE_LIST();
        model.addAttribute("houseTypeList", houseTypeList);
        return "insert";
    }

    @RequestMapping("insert")
    public String insert(@RequestParam("desc") String desc,
            @RequestParam("type")String type,
            @RequestParam("rent") int rent, Model model){

        House house = new House();
        house.setHouseDesc(desc);
        house.setMonthlyRent(rent);
        house.setPublishDate(new Date());
        int t = 0;
        if(type != null){
            t = Integer.parseInt(type);
        }
        house.setTypeId(t);
        int result = houseService.intsert(house);
        if(result > 0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
        return "redirect:/main2/findAll";
    }


}
